package com.ferryc.modules.sys.service.impl;

import java.util.List;

import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ferryc.commons.service.CommonService;
import com.ferryc.commons.utils.StringUtil;
import com.ferryc.constant.GlobalConstant;
import com.ferryc.modules.sys.entity.SysPermissions;
import com.ferryc.modules.sys.mapper.ISysPermissionsMapper;
import com.ferryc.modules.sys.service.ISysPermissionsService;

/**
 * 
 * 类名: ISysPermissionsService <br/>
 * 作用： 服务<br/>
 * 方法： <br/>
 * 创建者: Ferry C <br/>
 * 添加时间: 2017年12月02日 04:20:09 <br/>
 * 
 */
@Service
@Transactional(readOnly = true)
public class SysPermissionsServiceImpl extends CommonService<SysPermissions> implements ISysPermissionsService {

	@Autowired
	private ISysPermissionsMapper sysPermissionsMapper;

	@Override
	protected void init() {
		super.mapper = sysPermissionsMapper;
	}

	@Override
	@Transactional(readOnly = false)
	public void insertPermission(SysPermissions sysPermissions) {
		sysPermissionsMapper.insert(sysPermissions);
		insertPermissonMenu(sysPermissions);
	}

	@Override
	@Transactional(readOnly = false)
	public void deletePermissions(SysPermissions sysPermissions) {
		sysPermissionsMapper.update(sysPermissions);
		sysPermissionsMapper.deletePermissionsMenu(sysPermissions.getId());

	}

	@Override
	@Transactional(readOnly = false)
	public void updatePermissions(SysPermissions sysPermissions) {
		sysPermissionsMapper.update(sysPermissions);
		sysPermissionsMapper.deletePermissionsMenu(sysPermissions.getId());
		insertPermissonMenu(sysPermissions);
	}

	/**
	 * 插入权限菜单 表
	 * 
	 * @param sysPermissions
	 */
	@Transactional(readOnly = false)
	private void insertPermissonMenu(SysPermissions sysPermissions) {
		String menuId = sysPermissions.getMenuIds();
		String[] mArr = menuId.split(",");
		for (int i = 0; i < mArr.length; i++) {
			SysPermissions menuPerm = new SysPermissions();
			menuPerm.setPermissionId(sysPermissions.getId());
			menuPerm.setMenuId(mArr[i]);
			sysPermissionsMapper.insertPermissionsMenu(menuPerm);
			menuPerm = null;
		}
	}

	@Override
	public boolean checkPermissionName(SysPermissions sysPermissions) {
		SysPermissions queryPerm = new SysPermissions();
		queryPerm.setStatus(StringUtil.EMPTY);
		queryPerm.setDelFlag(GlobalConstant.DEL_FLAG_NORMAL);
		queryPerm.setPermissionName(sysPermissions.getPermissionName());

		List<SysPermissions> list = sysPermissionsMapper.listByEntity(queryPerm);
		if (CollectionUtils.isEmpty(list)) {
			return true;
		}
		if (StringUtil.isBlank(sysPermissions.getId())) {
			return false;
		} else {
			if (list.size() == 1 && list.get(0).getId().equals(sysPermissions.getId())) {
				return true;
			}
			return false;
		}
	}

 

}